package site.xuqing.autohelperengine.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.widget.Toast;

import java.util.List;

public class AppUtil {
    public static void startAppByAppName(Context context,String appName){
        PackageManager packageManager = context.getPackageManager();
        // 获取手机里的应用列表
        List<PackageInfo> pInfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pInfo.size(); i++){
            PackageInfo p = pInfo.get(i);
            // 获取相关包的<application>中的label信息，也就是-->应用程序的名字
            String label = packageManager.getApplicationLabel(p.applicationInfo).toString();
            System.out.println(label);
            //比较label
            if (label.equals(appName)){
                //获取包名
                String pName = p.packageName;
                Intent intent =packageManager.getLaunchIntentForPackage(pName);
                context.startActivity(intent);
            }
        }
    }

    /*
     * 启动一个app
     */
    public static void startAPP(Context context,String appPackageName){
        try{
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackageName);
            intent.setPackage(null); // 加上这句代码，解决打开到LAUNCHER的问题
            context.startActivity(intent);
        }catch(Exception e){
            Toast.makeText(context, "没有安装该App", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 程序进入后台
     */
    public static void gotoDesktop(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        context.startActivity(intent);
    }
}
